package com.likou.second_challenge;

import java.util.*;

public class q15 {

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        int n = nums.length;
        if (n < 3) {
            return ans;
        }

        Arrays.sort(nums);
        for (int i = 0; i < n - 2; i++) {
            int left = i + 1;
            int right = n - 1;
            if (nums[i] > 0) {
                break;
            }
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    ans.add(List.of(nums[i], nums[left], nums[right]));
                    int r = nums[right];
                    while (left < right && nums[right] == r) {
                        right--;
                    }
                    int l = nums[left];
                    while (left < right && nums[left] == l) {
                        left++;
                    }
                } else if (sum > 0) {
                    int r = nums[right];
                    while (left < right && nums[right] == r) {
                        right--;
                    }
                } else {
                    int l = nums[left];
                    while (left < right && nums[left] == l) {
                        left++;
                    }
                }
            }

        }

        return ans;
    }

}
